var express = require('express');
var router = express.Router();
var path = require('path');
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/douban';

/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });

router.post('/loginAction',function(req, res, next){
  var username = req.body.username;
  var password = req.body.password;

  MongoClient.connect(DB_CONN_STR,function(err, db){
    if(err){
      return;
    }else{
      var conn = db.collection('users');
      var data = {
        username:username,
        password:password
      };

      console.log(data.username+'------'+data.password);

      conn.find(data).toArray(function(err, results){
        if(results.length > 0){
          req.session.username = results[0].username;
          res.redirect('/');
        }else{
          res.send("请输入正确的用户名密码");
        }
      });
    }
  });
});

router.post('/registorAction',function(req,res,next){
    var username = req.body.username;
    var password = req.body.password;

    MongoClient.connect(DB_CONN_STR,function(err,db){
      if(err){
        return;
      }else{
        var conn = db.collection('users');
        var data = {
          username:username,
          password:password
        };

        conn.insert(data,function(err,results){
          res.send('user add success');
          db.close();
        });
      }
    });
});

module.exports = router;
